package com.yyc.stocktake

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.KeyEvent
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.activity.viewModels
import androidx.core.view.GravityCompat
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.navigation.NavOptions
import androidx.navigation.Navigation
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.navigateUp
import androidx.navigation.ui.onNavDestinationSelected
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.StringUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.android.material.navigation.NavigationView
import com.yyc.stocktake.api.UIHelper
import com.yyc.stocktake.base.BaseActivity
import com.yyc.stocktake.bean.RfidStateBean
import com.yyc.stocktake.databinding.AMainBinding
import com.yyc.stocktake.ext.RFID_TAG
import com.yyc.stocktake.ext.SCAN_STATUS_SCAN
import com.yyc.stocktake.ext.showMessage
import com.yyc.stocktake.keyctrl.Common
import com.yyc.stocktake.keyctrl.IKeyRecv
import com.yyc.stocktake.keyctrl.KeyRecerver
import com.yyc.stocktake.keyctrl.ScanThread
import com.yyc.stocktake.keyctrl.ScanType
import com.yyc.stocktake.keyctrl.ThreadPoolManager
import com.yyc.stocktake.keyctrl.entity.TagFindParam
import com.yyc.stocktake.util.CacheUtil
import com.yyc.stocktake.util.MusicUtils
import com.yyc.stocktake.viewmodel.AssetModel
import com.yyc.stocktake.viewmodel.AssetSearchmModel
import com.yyc.stocktake.viewmodel.RfidModel
import me.hgj.jetpackmvvm.ext.navigateAction
import rfid.uhfapi_y2007.core.Util
import rfid.uhfapi_y2007.entities.MemoryBank
import rfid.uhfapi_y2007.entities.TagParameter
import rfid.uhfapi_y2007.protocol.vrp.MsgPowerOff
import rfid.uhfapi_y2007.protocol.vrp.MsgTagInventory

class MainActivity : BaseActivity<RfidModel, AMainBinding>(), NavigationView.OnNavigationItemSelectedListener, IKeyRecv {

    lateinit var appBarConfiguration: AppBarConfiguration

    var shortPress = false

    private val assetModel: AssetModel by viewModels()

    private val assetSearchmModel: AssetSearchmModel by viewModels()

    private var scanThread: ScanThread? = null


    override fun initView(savedInstanceState: Bundle?) {
        KeyRecerver.setKeyRecvCallback(this)
        //注册广播接收
        registerReceiver()
        MusicUtils.init(this)
        lifecycle.addObserver(object : DefaultLifecycleObserver {
            override fun onPause(owner: LifecycleOwner) {
                super.onPause(owner)
                mViewModel.isOpen.value = false
            }

            override fun onStop(owner: LifecycleOwner) {
                super.onStop(owner)
                if (!AppUtils.isAppForeground()) {
                    //app 进入后台
                    mViewModel.isActive.set(false) //记录当前已经进入后台
                    mViewModel.isOpen.value = false
                }
            }

            override fun onDestroy(owner: LifecycleOwner) {
                super.onDestroy(owner)
                unregisterReceiver(keyReceiver)

                MusicUtils.clear()
                mViewModel.mIsContinuous.set(false)
                if (scanThread != null) {
                    scanThread!!.stopScan()
                    scanThread!!.interrupt()
                    scanThread!!.close()
                    scanThread = null
                }
            }
        })

        setSupportActionBar(mDatabind.appBarMain.includeToolbar.toolbar)
        val navController = findNavController(R.id.nav_host_fragment_content_main)
        appBarConfiguration = AppBarConfiguration(
            setOf(
                R.id.nav_order,
                R.id.nav_download,
                R.id.nav_upload,
                R.id.nav_rfid_config,
                R.id.nav_login
            ), mDatabind.drawerLayout
        )
        setupActionBarWithNavController(navController, appBarConfiguration)
        mDatabind.navView.setupWithNavController(navController)
        mDatabind.navView.setNavigationItemSelectedListener(this)
        mDatabind.appBarMain.includeToolbar.toolbar.run {
            setOnMenuItemClickListener {
                when (it.itemId) {
                    R.id.home_set -> {
                        mDatabind.drawerLayout.openDrawer(GravityCompat.END)
                    }
                }
                true
            }
        }

        scanThread = try {
            ScanThread(mHandler)
        } catch (e: Exception) {
            // 出现异常
            Toast.makeText(applicationContext, "serialport init fail", Toast.LENGTH_SHORT).show()
            return
            // e.printStackTrace();
        }
        scanThread?.start()
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.home_menu, menu)
        // 设置第一个菜单项为选中状态
        findViewById<NavigationView>(R.id.nav_view).setCheckedItem(R.id.nav_order)
        return true
    }

    override fun onSupportNavigateUp(): Boolean {
        val navController = findNavController(R.id.nav_host_fragment_content_main)
        return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
    }

    override fun onNavigationItemSelected(menuItem: MenuItem): Boolean {
        val navController = findNavController(R.id.nav_host_fragment_content_main)
        // 获取当前目标 Fragment 的 ID
        val currentDestinationId = navController.currentDestination?.id
        when (menuItem.itemId) {
            R.id.nav_order -> {
                if (currentDestinationId == R.id.nav_order) return true
                UIHelper.startOrderFrg(navController)
            }
            R.id.nav_download -> {
                if (currentDestinationId == R.id.nav_download) return true
                UIHelper.startDownloadFrg(navController)
            }
            R.id.nav_upload -> {
                if (currentDestinationId == R.id.nav_upload) return true
                UIHelper.starUploadFrg(navController)
            }
            R.id.nav_rfid_config -> {
                if (currentDestinationId == R.id.nav_rfid_config) return true
                UIHelper.starRfidConfigFrg(navController)
            }
            R.id.nav_login -> {
                val user = CacheUtil.getUser()
                user?.Password = null
                CacheUtil.setUser(user)
                UIHelper.startLoginAct()
                ActivityUtils.finishAllActivities()
                return true
            }
        }
        supportActionBar?.setDisplayHomeAsUpEnabled(false);
        mDatabind.navView.getMenu().findItem(menuItem.itemId).isChecked = true
        mDatabind.drawerLayout.closeDrawers()
        return true
    }

    override fun createObserver() {
        super.createObserver()
        // rfid数据接收回调
        mViewModel.rfidData.observe(this, {
            mViewModel.mTotalCount += 1
            var tagId = mViewModel.rfidData.value!!.TagId
            if (tagId.contains(" ")) {
                tagId = tagId.replace(" ", "")
            }
            LogUtils.e(tagId, it.Rssi)
            //搜索/识别回调
            if (mViewModel.tagFindParam == null) {
                assetModel.epcData.value = RfidStateBean(
                    tagId = tagId,
                    scanStatus = SCAN_STATUS_SCAN,
                    rssi = it.Rssi
                )
            } else {
                assetSearchmModel.epcData.value = RfidStateBean(
                    tagId = tagId,
                    rssi = it.Rssi
                )
            }
        })

        //是否启动rdif
        mViewModel.isOpen.observe(this, { resultState ->
            if (resultState && mViewModel.initConn.get()) {
                mViewModel.onClean()
                mViewModel.startStat()
                if (Common.reader != null && Common.reader.isConnected) {
                    Common.reader.Send(MsgPowerOff()) // 先停止

                    //EPC
                    Common.selectEpcParam = TagParameter()
                    Common.scanType = ScanType.ScanEpc
                    Common.reader.Send(MsgTagInventory())
                    Common.selectEpcParam.MemoryBank = MemoryBank.EPCMemory

                    //TID
//                    Common.selectParam = TagParameter()
//                    Common.scanType = ScanType.ScanTid
//                    Common.reader.Send(MsgTagRead())
//                    Common.selectParam.MemoryBank = MemoryBank.TIDMemory

                    if (Common.isEnableBeep) ThreadPoolManager.getInstance()
                        .execute(mViewModel.threadBeep) // 蜂鸣线程
                    mViewModel.isScan.set(true)
                } else {
                    showMessage(message = "Connection failed")
                }
            } else {
                if (mViewModel.isScan.get()) {
                    mViewModel.isScan.set(false)
                    mViewModel.onClean()
                    mViewModel.disconn()
//                mViewModel.initStop()
                    mViewModel.stopStat()
                    LogUtils.e("读卡断开")
                }
            }
        })

        //指定搜索RFID
        mViewModel.isSearchOpen.observe(this, {
            if (StringUtils.isEmpty(it)) {
                mViewModel.tagFindParam = null
                mViewModel.isOpen.value = false
            } else {
                mViewModel.tagFindParam = TagFindParam()
                mViewModel.tagFindParam?.ScanMB = RFID_TAG
                mViewModel.tagFindParam?.Data = Util.ConvertHexStringToByteArray(it)
                mViewModel.tagFindParam?.Mask = Util.ConvertHexStringToByteArray(it)
                mViewModel.isOpen.value = true
            }
        })
    }

    //region 按键广播
    private var keyReceiver: KeyReceiver? = null
    fun registerReceiver() {
        keyReceiver = KeyReceiver()
        val filter = IntentFilter()
        filter.addAction("android.rfid.FUN_KEY")
        filter.addAction("android.intent.action.FUN_KEY")
        registerReceiver(keyReceiver, filter)
    }

    private inner class KeyReceiver : BroadcastReceiver() {

        override fun onReceive(context: Context, intent: Intent) {
            var keyCode = intent.getIntExtra("keyCode", 0)
            val keyDown = intent.getBooleanExtra("keydown", false)
            if (keyDown && !mViewModel.mIsPressed.get()) {
                // 根据需要在对应的按键的键值中开启扫描,
                when (keyCode) {
                    KeyEvent.KEYCODE_F1, KeyEvent.KEYCODE_F2, KeyEvent.KEYCODE_F3, KeyEvent.KEYCODE_F4, KeyEvent.KEYCODE_F5 -> {
                        //开启扫描
                        mViewModel.mIsPressed.set(true)
                        scanThread!!.scan()
                    }

                    else -> {
                        mViewModel.mIsPressed.set(true)
                        scanThread!!.scan()
                    }
                }
            } else {
                mViewModel.mIsPressed.set(false)
            }
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_F5
            || keyCode == KeyEvent.KEYCODE_F7
        ) {
            if (event!!.action == KeyEvent.ACTION_DOWN) {
                event!!.startTracking() //只有执行了这行代码才会调用onKeyLongPress的；
                if (event!!.repeatCount == 0) {
                    shortPress = true
                }
                return true
            }
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun OnKeyDown(keycode: Int) {
        LogUtils.e("OnKeyDown" + keycode)
    }

    override fun OnKeyUp(keycode: Int) {
        LogUtils.e("OnKeyUp" + keycode)
    }

    override fun onDestroy() {
        super.onDestroy()
        setSupportActionBar(null)
    }

    var exitTime = 0L
    override fun onBackPressed() {
        if (mDatabind.drawerLayout.isDrawerOpen(GravityCompat.END)) {
            mDatabind.drawerLayout.closeDrawers()
        } else {
            val nav = Navigation.findNavController(this@MainActivity, R.id.nav_host_fragment_content_main)
            if (nav.currentDestination != null && nav.currentDestination!!.id != R.id.nav_order) {
                //如果当前界面不是主页，那么直接调用返回即可
                nav.navigateUp()
            } else {
                //是主页
                if (System.currentTimeMillis() - exitTime > 2000) {
                    ToastUtils.showShort("再按一次退出程序")
                    exitTime = System.currentTimeMillis()
                } else {
                    finish()
                }
            }
        }
    }

    private val mHandler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            if (msg.what == ScanThread.SCAN) {
                val dataBytes = msg.data.getByteArray("dataBytes")
                if (dataBytes == null || dataBytes.size == 0) {
                    if (mViewModel.mIsContinuous.get()) {
                        scanThread?.scan()
                    }
                    return
                }
                var data = ""
                /*if (false) {  GBK格式
                    try {
                        data = String(dataBytes, 0, dataBytes.size, "GBK")
                    } catch (e: UnsupportedEncodingException) {
                        e.printStackTrace()
                    }
                } else {
                    data = String(dataBytes, 0, dataBytes.size)
                }*/
                data = String(dataBytes, 0, dataBytes.size)
                if (data == null || data == "") {
                    if (mViewModel.mIsContinuous.get()) {
                        scanThread?.scan()
                    }
                    return
                }
                mViewModel.scanData.value = data
                MusicUtils.play()
                if (mViewModel.mIsContinuous.get()) {
                    scanThread?.scan()
                }
            }
        }
    }

}